#!/usr/bin/python2.4
# -*- python -*-
#
# Copyright (C) 2008  Google, Inc. All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

'''TsumuFS, a NFS-based caching filesystem.'''

import sys
import optparse

import xattr

if __name__ == '__main__':
  format = None

  parser = optparse.OptionParser()
  parser.add_option('-g', '--get',
                    action='store',
                    type='string',
                    dest='attribute',
                    help=('Get an attribute by name, rather than '
                          'listing all of them.'))
  parser.add_option('-f', '--show-filename',
                    action='store_true',
                    dest='show_filename',
                    help=('Show the filename of each file specified on '
                          'the command line.'))
  (options, args) = parser.parse_args()

  if len(args) < 1:
    parser.error('You must specify at least one filename to read from.')

  for filename in args:
    attribs = xattr.xattr(filename)

    if options.attribute != None:
      if options.show_filename:
        format = '%(filename)s: %(value)s'
      else:
        format = '%(value)s'

      try:
        print format % {'filename': filename,
                        'value': attribs[options.attribute]}
      except NameError, e:
        if options.show_filename:
          print format % {'filename': filename}
      except IOError, e:
        print 'xattr: %s' % e.strerror

    else:
      if options.show_filename:
        format = '%(filename)s: %(key)s=%(value)s'
      else:
        format = '%(key)s=%(value)s'

      try:
        for key in attribs.keys():
          print format % {'filename': filename,
                          'key': key,
                          'value': attribs[key]}
      except IOError, e:
        print 'xattr: %s' % e.strerror
